#include "PTZController.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

PTZController::PTZController(QString baseUrl, QObject *parent)
    : QObject(parent)
    , _baseUrl(baseUrl)
{
    _networkManager = new QNetworkAccessManager(this);
    connect(_networkManager, &QNetworkAccessManager::finished,
            this, &PTZController::onReplyFinished);
}

void PTZController::sendControlCommand(const QString& value, int speed, int steps, int stop)
{
    // 1. 构建参数键值对
    KVQuery kvs;

    // 必选参数：控制方向/动作
    kvs.add("value", value.toStdString());

    // 可选参数：仅当传入有效值时添加
    if (speed != -1) {
        kvs.add("speed", std::to_string(speed));
    }
    if (steps != -1) {
        kvs.add("steps", std::to_string(steps));
    }
    if (stop != -1) {
        kvs.add("stop", std::to_string(stop));
    }

    // 2. 生成加密参数（包含token，移除secret）
    std::string queryStr = kvs.toCrpyString();
    qDebug() << "加密后的请求参数:" << QString::fromStdString(queryStr);

    // 3. 构建完整请求URL
    QUrl url(_baseUrl + "/xsw/api/ptz/control");
    url.setQuery(QString::fromStdString(queryStr));
    qDebug() << "发送控制请求:" << url.toString();

    // 4. 发送POST请求
    QNetworkRequest request(url);
    // 设置请求头（根据接口要求，此处使用默认表单格式）
    request.setHeader(QNetworkRequest::ContentTypeHeader,
                      "application/x-www-form-urlencoded");
    _networkManager->post(request, QByteArray());
}

void PTZController::onReplyFinished(QNetworkReply* reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        // 解析JSON响应
        QByteArray response = reply->readAll();
        QJsonObject json = QJsonDocument::fromJson(response).object();

        int code = json["code"].toInt();
        QString msg = json["msg"].toString();

        if (code == 0) {
            emit controlResult(true, "控制成功: " + msg);
        } else {
            emit controlResult(false, "控制失败[" + QString::number(code) + "]: " + msg);
        }
    } else {
        emit controlResult(false, "网络错误: " + reply->errorString());
    }
    reply->deleteLater();
}
